﻿using DragonSolution.Web.Common.Common;
using DragonSolution.Web.Data.Entity;
using DragonSolution.Web.UI.DAL;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Web;
using System.Web.Script.Serialization;

namespace DragonSolution.Web.UI.Ashx
{
    /// <summary>
    /// 上传文件（包括zip、img等）
    /// </summary>
    public class UploadFiles : IHttpHandler
    {
        private JavaScriptSerializer json = new JavaScriptSerializer();
        private string operateSuccess = "调用成功";
        private string operateFailed = "调用失败";
        private double fileMaxMB;//文件最大值
        private string fileExtendName;//文件扩展名
        private string fileSavePath;//文件保存路径
        private int isCompress;//是否需要压缩（0：不需要，1：需要）
        private string tableName= "Attachment";//文件对应数据库表名,这里文件统一用一张表
        private Attachment attachmentEntity;
        private MyDbContext db;

        public void ProcessRequest(HttpContext context)
        {
            string action = context.Request["action"];
            context.Response.ContentType = "text/html;charset=utf-8";
            var jsonObj = string.Empty;

            BaseController bc = new BaseController();
            db = bc.GetContext();

            switch (action)
            {
                case "FileUpload":
                    jsonObj = FileUpload(context);
                    break;
            }

            context.Response.Write(jsonObj);
        }

        public string FileUpload(HttpContext context)
        {
            try
            {
                HttpFileCollection hfcs = context.Request.Files;
                isCompress = Convert.ToInt32(context.Request["isCompress"]);
                fileMaxMB = Convert.ToDouble(context.Request["fileMaxMB"]);                
                fileExtendName = context.Request["fileExtendName"];
                //fileSavePath = context.Request["uploadPath"] + DateTime.Now.ToString("yyyy") + "/" + DateTime.Now.ToString("MM") + "/" + DateTime.Now.ToString("dd") + "/";
                fileSavePath = context.Request["uploadPath"] + "/";
                List<AttachmentInfo> attrList = new List<AttachmentInfo>();
                //保存文件的相对路径
                string savePath = HttpContext.Current.Server.MapPath(fileSavePath);
                if (!Directory.Exists(savePath))
                {
                    //目录不存在则新建目录
                    Directory.CreateDirectory(savePath);
                }

                for (int i = 0; i < hfcs.Count; i++)
                {
                    var hfc = hfcs[i];
                    string fileName = Path.GetFileName(hfc.FileName);
                    string exName = Path.GetExtension(fileName);//包含"."
                    int contentLength = hfc.ContentLength;
                    //string contentType = hfcs[i].ContentType;
                    string fileGuidName = Guid.NewGuid().ToString() + exName;
                    AttachmentInfo attr = new AttachmentInfo();
                    attr.FileName = fileName;
                    attr.FileUrl = fileSavePath + fileGuidName;

                    //验证
                    string error = VerifyFile(exName, contentLength);
                    if (!string.IsNullOrEmpty(error))
                    {
                        attr.ErrorInfo = error;
                        attr.UploadResult = false;
                    }
                    else
                    {
                        //1.传到磁盘
                        bool CompressReslut;
                        if (isCompress == 1)
                        {
                            //需要压缩图片并保存
                            byte[] fileBytes = ImageUtil.StreamToByte(hfcs[i].InputStream);
                            CompressReslut = ImageUtil.CompressImages(fileBytes, savePath + fileGuidName);
                        }
                        else {
                            //不需要压缩图片
                            CompressReslut = true;
                            //保存
                            hfc.SaveAs(savePath + fileGuidName);
                        }

                        if (!CompressReslut)
                        {
                            attr.ErrorInfo = "压缩图片失败";
                            attr.UploadResult = false;
                        }
                        //2.保存到数据库附件表
                        else
                        { 
                            attachmentEntity = new Attachment();
                            attachmentEntity.AttachmentName = fileName;
                            attachmentEntity.TableName = tableName;
                            attachmentEntity.AttachmentPath = fileSavePath + fileGuidName;
                            attachmentEntity.AttachmentSize = contentLength;
                            attachmentEntity.IsDelete = 0;
                            attachmentEntity.CreateTime = DateTime.Now;
                            //插入
                            db.Attachment.Add(attachmentEntity);
                            db.SaveChanges();
                            //返回插入的数据的ID
                            int resultId = attachmentEntity.AttachmentID;

                            //注：Attachment表中"所属表ID"字段值在提交时再赋值

                            attr.FileId = resultId;
                            attr.ErrorInfo = string.Empty;
                            attr.UploadResult = true;
                        }

                    }

                    attrList.Add(attr);
                }

                return json.Serialize(new { OperateResult = operateSuccess, ResponseData = attrList });
            }
            catch (Exception exp)
            {
                return json.Serialize(new { OperateResult = operateFailed, ResponseData = exp.Message });
            }
        }

        /// <summary>
        /// 验证文件扩展名和文件大小
        /// </summary>
        /// <param name="exName">扩展名</param>
        /// <param name="contentLength">文件大小</param>
        private string VerifyFile(string exName, int contentLength)
        {
            string error = string.Empty;
            string fileExtensionName = exName.Substring(1, exName.Length - 1).ToLower();

            //验证扩展名
            if (!fileExtendName.Contains(fileExtensionName))
            {
                error = "格式有误";
            }
            else
            {
                //验证文件大小
                if (contentLength > 0)
                {
                    if (contentLength * 1.0 / (1024 * 1024) > fileMaxMB)
                    {
                        error = "文件过大";
                    }
                }
            }
            return error;
        }

        public class AttachmentInfo
        {
            public int FileId { get; set; }
            public string FileName { get; set; }
            public bool UploadResult { get; set; }
            public string ErrorInfo { get; set; }
            public string FileUrl { get; set; }
            public double FileSize { get; set; }
        }

        public bool IsReusable
        {
            get
            {
                return false;
            }
        }
    }
}